//
//  GRJTool.m
//  GRJTolCayFrwk
//
//  Created by apple on 2017/3/1.
//  Copyright © 2017年 Global Barter. All rights reserved.
//

#import "GRJTool.h"

#import "GRJMacros.h"

@implementation GRJTool

+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

//获取现在时间
+ (NSString *)getNowTime
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *timeStr = [formatter stringFromDate:date];
    return timeStr;
}

//获取现在时间
+ (NSString *)getNowTimeWithSecond
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *timeStr = [formatter stringFromDate:date];
    return timeStr;
}

//获取当前时间
+(NSString *)getCurrentTime
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSInteger year = [dateComponent year];
    NSInteger month = [dateComponent month];
    return [NSString stringWithFormat:@"%ld-%ld",(long)year,(long)month];
}

//时间戳转换为时间
+ (NSString *)XtimestampToTime:(NSTimeInterval)timestamp
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *date = nil;
    date  = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSString *timeStr = [formatter stringFromDate:date];
    formatter = nil;
    return timeStr;
}

//时间戳转换为时间
+ (NSString *)timestampToTime:(NSTimeInterval)timestamp
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *date = nil;
    //    if (longOftimesTamp.length > 10) {
    date  = [NSDate dateWithTimeIntervalSince1970:timestamp / 1000];
    //    }else{
    //        date  = [NSDate dateWithTimeIntervalSince1970:timestamp];
    //    }
    NSString *timeStr = [formatter stringFromDate:date];
    formatter = nil;
    return timeStr;
}

//时间戳转换为时间
+ (NSString *)timestampToMouthTime:(NSTimeInterval)timestamp
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd HH:mm"];
    NSDate *date = nil;
    date  = [NSDate dateWithTimeIntervalSince1970:timestamp / 1000];
    NSString *timeStr = [formatter stringFromDate:date];
    formatter = nil;
    return timeStr;
}


//将时间转换为时间戳
+ (NSTimeInterval)timeToTimestamp:(NSString *)timeStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date = [formatter dateFromString:timeStr];
    NSTimeInterval timesp = [date timeIntervalSince1970];
    formatter = nil;
    return timesp;
}

//将时间转换为时间戳
+ (NSTimeInterval)XtimeToTimestamp:(NSString *)timeStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    NSDate *date = [formatter dateFromString:timeStr];
    NSTimeInterval timesp = [date timeIntervalSince1970];
    formatter = nil;
    return timesp;
}

//删除document下的图片
+(void)deleteImageInSandBoxDocument
{
    NSString *extension1 = @"png";
    NSString *extension2 = @"jpg";
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
    NSEnumerator *e = [contents objectEnumerator];
    NSString *filename;
    while ((filename = [e nextObject])) {
        
        if ([[filename pathExtension] isEqualToString:extension1] || [[filename pathExtension] isEqualToString:extension2]) {
            
            [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
        }
    }
}

//计算字符个数
+(int)convertToInt:(NSString*)strtemp
{
    int strlength = 0;
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
        
    }
    return strlength;
}


+(UIColor *)navBarBlueColor
{
    return [self colorWithHexString:@"#0077cc"];
}

// 一级标题(一)颜色
+(UIColor *)titleBlackColor{
    return [self colorWithHexString:@"#404040"];
}
// 一级标题(二)颜色
+(UIColor *)titleGrayColor{
    return [self colorWithHexString:@"#808080"];
}

+(UIColor *)lineColor
{
    return [UIColor colorWithRed:200/255.0f green:199/255.0f blue:204/255.0f alpha:1];
}
// 标题返回橙黄色
+(UIColor *)titleYellowColor{
    return [self colorWithHexString:@"#fe8c14"];
}

+ (UIColor *)titleRedColor
{
    return [self colorWithHexString:@"#cc0000"];
}

+ (UIColor *)titleBlueColor
{
    return [self colorWithHexString:@"#0077CC"];
}

//判断对象是否为空
+(BOOL)objectIsEmpty:(id)object
{
    if ([object isEqual:[NSNull null]]) {
        return YES;
    }
    else if ([object isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    else if (nil == object){
        return YES;
    }
    return NO;
}

//若字符串为空，则默认将空字符串赋为@""
+(NSString *)convertString:(id)object
{
    
    if ([object isEqual:[NSNull null]]) {
        return @"";
    }
    else if ([object isKindOfClass:[NSNull class]])
    {
        return @"";
    }
    else if (nil == object){
        return @"";
    }
    return object;
}

//若字符串为空，则默认将空字符串赋为@"未加载数据"
+(NSString *)convertNULLString:(id)object
{
    
    if ([object isEqual:[NSNull null]]) {
        return @"";
    }
    else if ([object isKindOfClass:[NSNull class]])
    {
        return @"";
    }
    else if (nil == object){
        return @"";
    }
    return object;
}

//判断字典是否有某key值
+(BOOL)dicContainsKey:(NSMutableDictionary *)dic keyValue:(NSString *)key
{
    
    if ([self objectIsEmpty:dic]) {
        return NO;
    }
    
    NSArray *keyArray = [dic allKeys];
    
    if ([keyArray containsObject:key]) {
        
        return YES;
    }
    return NO;
}

+(UIColor *)bgViewWhite
{
    return [self colorWithHexString:@"#f2f2f2"];
}

//内部蓝色字体
+(UIColor *)steelInnerBlueColor
{
    return [self colorWithHexString:@"#0077cc"];
}

+(UIColor *)steelDarkGrayBlack
{
    return [self colorWithHexString:@"#404040"];
}

/** 验证手机号码 */
+ (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    NSPredicate *regextestphs = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES)
        || ([regextestphs evaluateWithObject:mobileNum] == YES)
        )
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


/**判断输入的字符串是否为纯数字 */

//判断是否为整形：
+ (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//判断是否为浮点形
+ (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

//判断是否符合身份证号码
+ (BOOL)validateIdentificationFormat:(NSString *)identification
{
    BOOL flag;
    if (identification.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identification];
}

// 获取当前系统的时间戳
+ (NSString *)getStrWithTime{
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    return timeString;
}

// 某一字符串是否包含另一个字符串
+ (BOOL)isfirst:(NSString *)first includeSecond: (NSString *)second{
    NSString *str = first;
    NSRange range = [str rangeOfString:second];
    if (range.location!=NSNotFound) {
        return YES;
    }else {
        return NO;
    }
}

// 计算文件夹下所有文件的大小
+(long)fileSizeForDir:(NSString*)path{
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    long size = 0;
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    for(int i = 0; i<[array count]; i++){
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
        BOOL isDir;
        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) ){
            NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
            size+= fileAttributeDic.fileSize;
        }else{
            [self fileSizeForDir:fullPath];
        }
    }
    return size/(1024*1024);
}

/* 统一设置上传图片的大小 **/
+ (UIImage *)scaleToSize:(UIImage *)img{
    // 图片比例
    CGFloat realPer = 1.0;
    if (img.size.width > IMAGEXY) { // 宽度大于屏幕的宽度
        realPer = IMAGEXY / img.size.width;
    }else if (img.size.height > IMAGEXY) { // 宽度高于屏幕的高度
        realPer = IMAGEXY / img.size.width;
    }else{// 原比例
        realPer = 1.0;
    }
    // 固定图片的宽度
    CGFloat realWidth = img.size.width * realPer;
    // 等比缩放图片的高度
    CGFloat realHeight = img.size.height * realPer;
    // 获取图片新的尺寸
    CGSize E = CGSizeMake(realWidth, realHeight);
    // 创建context
    UIGraphicsBeginImageContext(E);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, E.width, E.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}

/** 判断是否为URL */
+ (BOOL)isUrl{
    NSString *regex = @"http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:self];
}

+ (NSString *) md5:(NSString *) input
{
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}

+ (NSString *)stringByDecodingURLFormat
{
    NSString *result = [(NSString *)self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}


+ (NSString *)generateThePendingSignatureStringWithDict: (NSDictionary *)dict{
    NSArray *keys= [[dict allKeys]sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < keys.count; i++) {
        NSString *str = [NSString stringWithFormat:@"%@=%@", keys[i], dict[keys[i]]];
        [tempArray addObject:str];
    }
    NSString *newStr = tempArray[0];
    for (int i = 1; i < tempArray.count; i++) {
        NSString *tempStr = tempArray[i];
        newStr = [newStr stringByAppendingFormat:@"&%@", tempStr];
    }
    NSString *resultString = [newStr stringByAppendingString:@"o08cka6xb0reura1o44izrbgfmh0jkcn"];
    PCLog(@"%@", resultString);
    return resultString;
}

+ (NSString *)generateTheVerifyWithDict: (NSDictionary *)dict{
    NSMutableDictionary *newDict = [dict mutableCopy];
    NSArray *removeKey = @[@"action", @"verify"];
    [newDict removeObjectsForKeys:removeKey];
    NSArray *keys= [[newDict allKeys]sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < keys.count; i++) {
        NSString *key = keys[i];
        NSString *str = [NSString stringWithFormat:@"%@=%@", [key lowercaseString], newDict[keys[i]]];
        [tempArray addObject:str];
    }
    NSString *newStr = tempArray[0];
    for (int i = 1; i < tempArray.count; i++) {
        NSString *tempStr = tempArray[i];
        newStr = [newStr stringByAppendingFormat:@"&%@", tempStr];
    }
    newStr = [newStr stringByAppendingString:@"jiankang"];
    return newStr;
}



@end
